<template>
  <div class="ft-form-page">
    <!-- 顶部：返回 | 新增/编辑 -->
    <div class="page-header">
      <a-button type="link" class="back" @click="onBack">
        <LeftOutlined class="back-icon" />
        返回
      </a-button>
      <span class="sep">|</span>
      <span class="title">{{ pageTitle }}</span>
    </div>

    <!-- 新增父级 -->
    <div class="content-area">
      <!-- 表单 -->
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ style: 'width: 88px;' }"
        :wrapper-col="{ style: 'max-width: 720px;' }"
        class="form"
      >
        <a-form-item label="名称：" name="name">
          <a-input v-model:value="form.name" placeholder="请输入" allow-clear />
        </a-form-item>

        <a-form-item label="启用状态：">
          <a-radio-group v-model:value="form.enabled">
            <a-radio :value="true">启用</a-radio>
            <a-radio :value="false">停用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>

      <!-- 底部 -->
      <div class="page-footer">
        <div class="footer-inner">
          <a-button type="link" class="btn-cancel" @click="onBack"
            >取消</a-button
          >
          <span class="sep">|</span>
          <a-button
            type="link"
            class="action"
            :loading="submitting"
            @click="onSubmit"
            >确定</a-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, onMounted } from "vue";
import type { FormInstance } from "ant-design-vue";
import { message } from "ant-design-vue";
import { useRoute, useRouter } from "vue-router";
import { LeftOutlined } from "@ant-design/icons-vue";

import {
  createForbidden,
  updateForbidden,
  type ForbiddenStatus,
} from "@/api/modules/forbiddenTerms.api";

type Mode = "create" | "edit";
type RowLike = {
  id?: string | number;
  name?: string;
  enabled?: boolean;
  status?: "enabled" | "disabled";
};

const router = useRouter();
const route = useRoute();

const TAB_KEY = "forbidden";

const formRef = ref<FormInstance>();
const submitting = ref(false);
const mode = ref<Mode>("create");
const editingId = ref<string | number | null>(null);

/** 表单数据 */
const form = reactive<{ name: string; enabled: boolean }>({
  name: "",
  enabled: true,
});

/** 页面标题 */
const pageTitle = computed(() => (mode.value === "edit" ? "编辑" : "新增"));

/** 规则 */
const rules = {
  name: [
    { required: true, message: "请输入名称" },
    {
      validator(_: any, v: string) {
        if (!v) return Promise.resolve();
        const cleaned = v.trim();
        return cleaned ? Promise.resolve() : Promise.reject("请输入有效名称");
      },
    },
  ],
};

/** 进入时：判断模式 & 回显数据 */
onMounted(() => {
  const raw = Array.isArray(route.query.row)
    ? route.query.row[0]
    : (route.query.row as string | undefined);
  const idFromQuery = route.query.id as string | number | undefined;

  if (raw) {
    try {
      const obj: RowLike = JSON.parse(decodeURIComponent(raw));
      editingId.value = obj?.id ?? idFromQuery ?? null;
      if (obj?.name != null) form.name = String(obj.name).trim();
      if (typeof obj?.enabled === "boolean") form.enabled = obj.enabled;
      else if (obj?.status) form.enabled = obj.status === "enabled";
      mode.value = "edit";
      return;
    } catch {
      /* ignore */
    }
  }

  if (idFromQuery != null) {
    editingId.value = idFromQuery;
    mode.value = "edit";
  } else {
    mode.value = "create";
  }
});


function onBack() {
  router.push({ path: "/", query: { tab: TAB_KEY } });
}


function normalizeName(input: string) {
  return input.trim().replace(/\s+/g, " ");
}
async function onSubmit() {
  try {
    submitting.value = true;
    await formRef.value?.validate();

    const name = normalizeName(form.name);
    const status: ForbiddenStatus = form.enabled ? "published" : "draft";

    if (mode.value === "edit" && editingId.value != null) {
      await updateForbidden(editingId.value, { query: name, status });
      message.success("保存成功");
    } else {
      await createForbidden({ query: name, status });
      message.success("新增成功");
    }

    onBack();
  } catch (err: any) {
    if (err?.errorFields) return;
    message.error(err?.message || "操作失败，请稍后重试");
  } finally {
    submitting.value = false;
  }
}
</script>

<style lang="less" scoped>
@pad-x: 24px;
@label-w: 88px;
@wrap-max: 720px;
@safe-bottom: env(safe-area-inset-bottom);

.ft-form-page {
  font-family: "PingFang SC", -apple-system, BlinkMacSystemFont, "Segoe UI",
    Roboto, "Helvetica Neue", Arial, sans-serif;

  :deep(.ant-*) {
    font-family: inherit;
  }

  height: 100%;
  min-height: 100vh;
  min-height: 100dvh;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  overflow: hidden;


  .page-header {
    flex: 0 0 auto;
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 24px 0;

    .back.ant-btn {
      display: inline-flex;
      align-items: center;
      padding: 0 12px 0 @pad-x;
      height: 24px;
      line-height: 24px;
      font-size: 14px;
      color: #81889c;

      .back-icon {
        font-size: 16px;
        line-height: 1;
        color: inherit;
      }
    }

    .sep {
      height: 24px;
      line-height: 24px;
      color: #d9d9d9;
      user-select: none;
    }
    .title {
      height: 24px;
      line-height: 24px;
      font-weight: 500;
      font-size: 16px;
      color: #000;
    }
  }


  .content-area {
    flex: 1 1 auto;
    min-height: 0; 
    display: flex;
    flex-direction: column;
    overflow-y: auto; 
    overflow-x: hidden;
    -webkit-overflow-scrolling: touch;
    overscroll-behavior: contain;
    padding-bottom: calc(16px + @safe-bottom);

    &::-webkit-scrollbar {
      width: 10px;
      height: 10px;
    }
    &::-webkit-scrollbar-thumb {
      background: rgba(0, 0, 0, 0.15);
      border-radius: 6px;
      border: 2px solid transparent;
      background-clip: padding-box;
    }
    &::-webkit-scrollbar-thumb:hover {
      background: rgba(0, 0, 0, 0.25);
    }
    &::-webkit-scrollbar-track {
      background: transparent;
    }
    scrollbar-width: thin;
    scrollbar-color: rgba(0, 0, 0, 0.25) transparent;
    scrollbar-gutter: stable;
  }

  .form {
    padding: 24px @pad-x 0 @pad-x;

    :deep(.ant-form-item) {
      margin-bottom: 24px;
    }
    :deep(.ant-form-item-label > label) {
      height: 24px;
      line-height: 24px;
      font-size: 14px;
      color: #333;
    }
    :deep(.ant-form-item-control) {
      min-height: 24px;
    }
  }

  .page-footer {
    position: static;
    margin-top: 16px;
    padding: 12px @pad-x calc(12px + @safe-bottom) @pad-x;
    background: #fff;
    border-top: 1px solid #f0f0f0;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.03);

    .footer-inner {
      max-width: @wrap-max;
      margin: 0 auto; 
      display: flex;
      align-items: center;
      justify-content: center; 
      gap: 12px;
      flex-wrap: wrap;
      width: 100%;
    }

    .sep {
      color: #e5e7eb;
      user-select: none;
      line-height: 24px;
      height: 24px;
      display: inline-flex;
      align-items: center;
      margin: 0 2px;
    }

    /* 取消按钮 */
    .btn-cancel {
      height: 36px;
      padding: 0 16px;
      border-radius: 8px;
      background: #fafafa !important;
      border: 1px solid #e8e8e8 !important;
      color: #666 !important;
      transition: all 0.2s ease;
    }
    .btn-cancel:hover {
      background: #fff !important;
      border-color: #d9d9d9 !important;
      color: #595959 !important;
    }

    .action {
      height: 36px;
      padding: 0 20px;
      border-radius: 8px;
      font-weight: 600;
      background: #1677ff !important;
      border: 1px solid #1677ff !important;
      color: #fff !important;
      transition: box-shadow 0.2s ease, filter 0.2s ease;
    }
    .action:hover {
      filter: brightness(1.02);
      box-shadow: 0 2px 8px rgba(22, 119, 255, 0.2);
    }
    .action[disabled],
    .action[disabled]:hover {
      background: #69b1ff !important;
      border-color: #69b1ff !important;
      box-shadow: none;
      color: #fff !important;
      opacity: 0.85;
    }
  }

  /* 小屏优化 */
  @media (max-width: 576px) {
    .page-header {
      padding: 16px 0;
    }
    .form {
      padding: 16px 12px 0 85px;
    }
    .page-footer {
      padding-left: 12px;
      padding-right: 12px;
    }
  }
}


.top-divider,
.bottom-divider {
  display: none;
}
</style>
